package com.ygqh.baby.service.alipay.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.xml.XmlStream;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.http.YgRequestExecutor;
import com.ygqh.baby.http.YgResponse;
import com.ygqh.baby.service.alipay.model.AliDeclareCustomsResult;
import com.ygqh.baby.service.alipay.model.AliQueryCustomsResult;
import com.ygqh.baby.service.alipay.model.AliSyncBaseResult;
import com.ygqh.baby.service.alipay.sign.MD5;
import com.ygqh.baby.service.alipay.util.AlipayCore;
import com.ygqh.baby.service.wechat.model.DeclareCustomsResult;
import com.ygqh.baby.utils.MapUtil;

@Component
public class AlipayApi {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do";
	private static final String DECLARE_CUSTOMS_SERVICE = "alipay.acquire.customs";
	private static final String QUERY_CUSTOMS_SERVICE = "alipay.overseas.acquire.customs.query";
	
	@Value("${alipay.charset}")
	private String charset;
	@Value("${alipay.partner}")
	private String partner;
	@Value("${alipay.seller_id}")
	private String sellerId;
	@Value("${alipay.key}")
	private String key;
	@Value("${alipay.sign_type}")
	private String signType;
	private YgRequestExecutor requestExecutor = new YgRequestExecutor();
	

	/**
	 * 报关
	* @Title: declareCustoms 
	*  @param declareCustoms    入参
	* @return void    返回类型
	* @author （guohao） 
	* @throws
	* @date 2018年11月19日 下午7:12:37 
	* @version V1.0
	 * @throws YgHttpException 
	 */
	public void declareCustoms(DeclareCustomsModel declareCustoms) throws YgHttpException {
		buildApplicationParam(declareCustoms,DECLARE_CUSTOMS_SERVICE);
		logger.info("支付宝申报海关 -> request：{}",JSON.toJSONString(declareCustoms));
		YgResponse response = execute(declareCustoms);	
		logger.info("支付宝申报海关 -> response：{}",response.getAsString());
		AliDeclareCustomsResult result = this.getAsObject(response.getAsString(), new TypeReference<AliDeclareCustomsResult>() {
		});
	}
	
	public void queryCustoms(String outRequestNos) {
		QueryCustoms queryCustoms = new QueryCustoms(); 
		queryCustoms.setOutRequestNos(outRequestNos);
		buildApplicationParam(queryCustoms,QUERY_CUSTOMS_SERVICE);
		try {
			YgResponse response = execute(queryCustoms);
			AliQueryCustomsResult result = this.getAsObject(response.getAsString(), new TypeReference<AliQueryCustomsResult>() {
			});
		} catch (YgHttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	private <T extends BaseAlipayModel> YgResponse execute(T t) throws YgHttpException{
		

		String jsonString = JSONObject.toJSONString(t);
		Map<String, String> param = convertToMap(jsonString);
		Map<String, String> paraFilter = AlipayCore.paraFilter(param);
		String signStr = AlipayCore.createLinkString(paraFilter);
//		String signStr = MapUtil.toJoinString(param, false,  false);
		String sign = MD5.sign(signStr, key, charset);
		param.put("sign",sign);
		return this.doExecute(param);
	}
	
	private YgResponse doExecute(Map<String, String> param) throws YgHttpException{
			logger.info(JSON.toJSONString(param));
			YgResponse post = requestExecutor.post(ALIPAY_GATEWAY_NEW, param);
			return post;
	}
	
	private <T extends BaseAlipayModel> void buildApplicationParam(T t, String service){
		t.setService(service);
		t.setPartner(partner);
		t.setSignType(signType);
		t.setInputCharset(charset);
	}
	
	private Map<String,String> convertToMap(String jsonStr){
		Map<String, String> param = new HashMap<String, String>();
		JSONObject obj = JSONObject.parseObject(jsonStr);
		for (String key : obj.keySet()) {
			param.put(key, obj.getString(key));
		}
		return param;
	}
	
	public <T> T getAsObject(String StrXml,TypeReference<T> typeReference) {
		 
		@SuppressWarnings("unchecked")
		Class<T> clazz = (Class<T>) typeReference.getType();
		return XmlStream.fromXML(StrXml, clazz);
}
	public static void main(String[] args) throws YgHttpException, IOException {
		DeclareCustomsModel d= new DeclareCustomsModel();
		d.setAmount("4564654564");
		d.setMerchantCustomsCode("4445");
		
		AlipayApi alipayApi = new AlipayApi();
		
		alipayApi.queryCustoms("123456");
	}
}
